import axios from "axios";
import { message } from "ant-design-vue";

// 取消请求操作
const allPendingRequestsRecord = [];
const pending = {};

const removeAllPendingRequestsRecord = () => {
  allPendingRequestsRecord &&
    allPendingRequestsRecord.forEach(func => {
      // 取消请求（调用函数就是取消该请求）
      func("路由跳转了取消所有请求");
    });
  // 移除所有记录
  allPendingRequestsRecord.splice(0);
};

// 取消同一个重复的ajax请求
const removePending = (key, isRequest = false) => {
  if (pending[key] && isRequest) {
    pending[key]("取消重复请求");
  }
  delete pending[key];
};

// 取消所有请求的函数
export const getConfirmation = (mes = "", callback = () => { }) => {
  removeAllPendingRequestsRecord();
  callback();
};

const fetch = axios.create({
  baseURL: "/",
  timeout: 30 * 1000,
});

fetch.interceptors.request.use(
  config => {
    // 在请求发送前执行一下取消操作，防止连续点击重复发送请求(例如连续点击2次按钮)
    let reqData = "";
    // 处理如url相同请求参数不同时上一个请求被屏蔽的情况
    if (config.method === "get") {
      reqData = config.url + config.method + JSON.stringify(config.params);
    } else {
      reqData = config.url + config.method + JSON.stringify(config.data);
    }
    removePending(reqData, true);
    // 设置请求的 cancelToken（设置后就能中途控制取消了）
    config.cancelToken = new axios.CancelToken(c => {
      pending[reqData] = c;
      allPendingRequestsRecord.push(c);
    });

    config.headers["X-Requested-With"] = "XMLHttpRequest";
    return config;
  },
  error => {
    console.log(error);
    Promise.reject(error);
  }
);

fetch.interceptors.response.use(
  response => {
    let res = response.data;

    if (res.code === "-304") {
      window.location.href = "/login";
    } else {
      return res;
    }
  },
  error => {
    // 终结由于取消重复请求而引发的报错提示
    if (axios.isCancel(error)) {
      return new Promise(() => { });
    }
    if (error.response) {
      if (error.response.status === 401) {
        window.location.href = "/login";
      } else if (error.response.status === 403) {
        window.location.href = "/login";
      } else if (error.response.status === 511) {
        window.location.href = "/login";
      } else {
        message.error("网络连接异常");
      }
    }
    console.log("err" + error);
    return Promise.reject(error);
  }
);

export default fetch;
